package com.tencent50.easy;

/**
 * @author: zhengtao
 * @description: 二叉搜索树的最近公共祖先,查看答案做出来的,
 * @version: 1.0
 * @date: 2022/07/25  22:23
 */
public class Demo18 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root.val== p.val){
            return p;
        }else if(root.val==q.val){
            return q;
        }else if(p.val< root.val&&q.val< root.val){
            return lowestCommonAncestor(root.left,p,q);
        }else if(p.val> root.val&&q.val>root.val){
            return lowestCommonAncestor(root.right,p,q);
        }else {
            return root;
        }

    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) {
            val = x;
        }
    }
}
